Page({
  data: {
    account: '',
    password: '',
    identityArray: ['普通学生', '励志委员', '励志辅导站助理', '辅导员', '学校人员'],
    identityIndex: 0, // 默认选中普通学生
  },

  onLoad: function() {
    // 页面加载时从本地存储获取账号密码
    const storedAccount = wx.getStorageSync('account');
    const storedPassword = wx.getStorageSync('password');
    
    if (storedAccount && storedPassword) {
      this.setData({
        account: storedAccount,
        password: storedPassword,
      });
    }
  },
  
  onAccountInput(e) {
    this.setData({
      account: e.detail.value.trim(),
    });
  },
  
  onPasswordInput(e) {
    this.setData({
      password: e.detail.value.trim(),
    });
  },
  
  onLogin() {
    
    if (!this.data.account || !this.data.password) {
      wx.showToast({
        title: '账号或密码不能为空',
        icon: 'none',
      });
      return;
    }

    this.setData({
      account:this.data.account,
      password:this.data.password
    });

    wx.cloud.callFunction({
      name:"User_manage",
      config: {
        env: this.data.envId
      },
      data:{
        type:"login",
        data:{
          account:'s'+this.data.account,
          password:'s'+this.data.password,
          index:this.data.identityIndex
        }
      },
      success:res=>{
        if (res.result.success) {
          wx.setStorageSync('account', this.data.account);
          wx.setStorageSync('password', this.data.password);
          const app = getApp();
          app.globalData.global_account=this.data.account;
          switch(this.data.identityIndex){
            case 0:
              wx.navigateTo({
                url: '/pages/navigation/navigation?account='+'s'+this.data.account,
              });
              break;
            case 1:
              wx.navigateTo({
                url: '/pages/hreviewn/hreviewn1/hreviewn1?account='+'s'+this.data.account,
              });
              break;
            case 2:
              wx.navigateTo({
                url: '/pages/hreviewn/hreviewn2/hreviewn2?account='+'s'+this.data.account,
              });
              break;
            case 3:
              wx.navigateTo({
                url: '/pages/hreviewn/hreviewn3/hreviewn3?account='+'s'+this.data.account,
              });
              break;
            case 4:
              wx.navigateTo({
                url: '/pages/hreviewn/hreviewn4/hreviewn4?account='+'s'+this.data.account,
              });
              break;
          }
        } else {
          console.log(res.result.message)
          wx.showToast({
            title: '账号或密码错误',
            icon: 'none',
          });
        }
      },
      fail:res=>{
        console.log(res);
        wx.showToast({
          title: '连接数据库失败',
          icon: 'none',
        });
      }
    })

    // 判断身份并进行相应的账号密码验证逻辑
  }, 
  
  // 身份切换
  onIdentityChange(e) {
    this.setData({
      identityIndex: parseInt(e.detail.value, 10),
    });
  },
});
